package com.css.zfzx.fxpg.modules.preestimate.report.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.components.attach.repository.entity.SysAttachmentEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.modules.attach.FxAttachmentRepository;
import com.css.zfzx.fxpg.modules.preestimate.report.repository.FxPreestimateReportNativeRepository;
import com.css.zfzx.fxpg.modules.preestimate.report.repository.FxPreestimateReportRepository;
import com.css.zfzx.fxpg.modules.preestimate.report.repository.entity.FxPreestimateReportEntity;
import com.css.zfzx.fxpg.modules.preestimate.report.service.FxPreestimateReportService;
import com.css.zfzx.fxpg.modules.preestimate.report.viewobjects.FxPreestimateReportQueryParams;
import com.css.zfzx.fxpg.modules.preestimate.report.viewobjects.FxPreestimateReportVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-18
 */
@Service
@Slf4j
public class FxPreestimateReportServiceImpl implements FxPreestimateReportService {

    @Autowired
    private FxPreestimateReportRepository fxPreestimateReportRepository;
    @Autowired
    private FxPreestimateReportNativeRepository fxPreestimateReportNativeRepository;
    @Autowired
    FxAttachmentRepository attachmentRepository;

    @Override
    public JSONObject queryFxPreestimateReports(FxPreestimateReportQueryParams queryParams, int curPage, int pageSize) {
        Page<FxPreestimateReportEntity> fxPreestimateReportPage = this.fxPreestimateReportNativeRepository.queryFxPreestimateReports(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxPreestimateReportPage);
        return jsonObject;
    }


    @Override
    public FxPreestimateReportEntity getFxPreestimateReport(String id) {
        FxPreestimateReportEntity fxPreestimateReport = this.fxPreestimateReportRepository.findById(id).orElse(null);
        return fxPreestimateReport;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPreestimateReportEntity saveFxPreestimateReport(FxPreestimateReportEntity fxPreestimateReport) {
        String uuid = UUIDGenerator.getUUID();
        fxPreestimateReport.setId(uuid);
        fxPreestimateReport.setCreateUser(PlatformSessionUtils.getUserId());
        fxPreestimateReport.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxPreestimateReportRepository.save(fxPreestimateReport);
        return fxPreestimateReport;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPreestimateReportEntity updateFxPreestimateReport(FxPreestimateReportEntity fxPreestimateReport) {
        fxPreestimateReport.setUpdateUser(PlatformSessionUtils.getUserId());
        fxPreestimateReport.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxPreestimateReport.getId();
        FxPreestimateReportEntity one = fxPreestimateReportRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxPreestimateReport, one);
        this.fxPreestimateReportRepository.save(one);
        return fxPreestimateReport;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxPreestimateReports(List<String> ids) {
        List<FxPreestimateReportEntity> fxPreestimateReportList = this.fxPreestimateReportRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxPreestimateReportList) && fxPreestimateReportList.size() > 0) {
            for (FxPreestimateReportEntity fxPreestimateReport : fxPreestimateReportList) {
                this.fxPreestimateReportRepository.delete(fxPreestimateReport);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxPreestimateReportVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxPreestimateReportVo.class, params);
            List<FxPreestimateReportVo> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxPreestimateReportVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxPreestimateReportVo reportVo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + reportVo.getRowNum() + "行" + reportVo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 保存Excel数据
     *
     * @param list
     */
    private void saveExcel(List<FxPreestimateReportVo> list) {
        FxPreestimateReportEntity reportEntity = new FxPreestimateReportEntity();
        for (FxPreestimateReportVo reportVo : list) {
            // VO数据拷贝到Entity中
            BeanUtils.copyProperties(reportVo, reportEntity);
            // 报告（简本）-文件上传
            String reportBriefFileName = reportVo.getReportBriefFileName().replace("\n", "");
            if (StringUtils.isNotBlank(reportBriefFileName)) {
                List<SysAttachmentEntity> attachmentEntities = attachmentRepository.findByAttachNameAndIsValid(reportBriefFileName, "1");
                if (attachmentEntities.size() > 0) {
                    // 业务一个文件名称一般对应一个文件
                    String attachId = attachmentEntities.get(0).getAttachId();
                    // 设置文件id和name
                    reportEntity.setReportBriefId(attachId);
                    reportEntity.setReportBriefName(reportBriefFileName);
                }
            }
            // 报告（详本）-文件上传
            String reportDetailFileName = reportVo.getReportDetailFileName().replace("\n", "");
            if (StringUtils.isNotBlank(reportDetailFileName)) {
                List<SysAttachmentEntity> attachmentEntities = attachmentRepository.findByAttachNameAndIsValid(reportDetailFileName, "1");
                if (attachmentEntities.size() > 0) {
                    // 业务一个文件名称一般对应一个文件
                    String attachId = attachmentEntities.get(0).getAttachId();
                    // 设置文件id和name
                    reportEntity.setReportDetailId(attachId);
                    reportEntity.setReportDetailName(reportDetailFileName);
                }
            }
            // 报告-文件上传
            String reportFileName = reportVo.getReportFileName().replace("\n", "");
            if (StringUtils.isNotBlank(reportFileName)) {
                List<SysAttachmentEntity> attachmentEntities = attachmentRepository.findByAttachNameAndIsValid(reportFileName, "1");
                if (attachmentEntities.size() > 0) {
                    // 业务一个文件名称一般对应一个文件
                    String attachId = attachmentEntities.get(0).getAttachId();
                    // 设置文件id和name
                    reportEntity.setReportId(attachId);
                    reportEntity.setReportName(reportFileName);
                }
            }
            this.saveFxPreestimateReport(reportEntity);
        }
    }


}
